﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyVigenereCipher
{
    internal class DecryModel
    {

        /// <summary>
        /// 明文
        /// </summary>
        public string DecryPlainText { get; set; }

        /// <summary>
        /// 密文
        /// </summary>
        public string DecryCipher { get; set; }

        /// <summary>
        /// 密钥
        /// </summary>
        public string DecryKey { get; set; }

        /// <summary>
        /// 解密过程
        /// </summary>
        public void Decode()
        {
            int length = DecryKey.Length;
            char[] decryPlainText = DecryPlainText.ToCharArray();
            char[] decryKey = DecryKey.ToCharArray();
            char[] decryCipher = new char[DecryPlainText.Length];
            //加密
            for (int i = 0; i < decryPlainText.Length; i++)
            {
                char ch = '0';
                int result = (GetNum(decryPlainText[i]) - GetNum(decryKey[i % length]) + 26) % 26;
                if ('a' <= decryPlainText[i] && decryPlainText[i] <= 'z')
                {
                    ch = Convert.ToChar(result + 'A');
                }
                if ('A' <= decryPlainText[i] && decryPlainText[i] <= 'Z')
                {
                    ch = Convert.ToChar(result + 'a');
                }
                decryCipher[i] = ch;
            }
            DecryCipher = new string(decryCipher);

        }

        /// <summary>
        /// 返回指定字符在字母表中的序号（从0开始）
        /// </summary>
        /// <param name="ch"></param>
        /// <returns></returns>
        private int GetNum(char ch)
        {
            int result = 0;
            if ('a' <= ch && ch <= 'z')
            { result = ch - 'a'; }
            if ('A' <= ch && ch <= 'Z')
            { result = ch - 'A'; }
            return result;
        }

    }
}
